package com.example.myapplicationktkt2.log

import android.content.Context
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.PrintWriter
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class Logger private constructor(private val context: Context) {
    companion object {
        private const val TAG = "Logger"
        private const val LOG_FILE_NAME = "app_log.txt"
        private var instance: Logger? = null

        fun init(context: Context) {
            if (instance == null) {
                instance = Logger(context)
            }
        }

        fun d(tag: String, message: String) {
            instance?.log('D', tag, message)
        }

        fun i(tag: String, message: String) {
            instance?.log('I', tag, message)
        }

        fun w(tag: String, message: String) {
            instance?.log('W', tag, message)
        }

        fun e(tag: String, message: String) {
            instance?.log('E', tag, message)
        }
    }

    private fun log(level: Char, tag: String, message: String) {
        val timestamp = SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss.SSS",
            Locale.getDefault()
        ).format(Date())
        val logMessage = "$timestamp $level/$tag: $message\n"

        // 输出到控制台
        when (level) {
            'D' -> Log.d(tag, message)
            'I' -> Log.i(tag, message)
            'W' -> Log.w(tag, message)
            'E' -> Log.e(tag, message)
        }

        // 写入文件
        writeToFile(logMessage)
    }

    private fun writeToFile(message: String) {
        try {
            val logFile = File(context.getExternalFilesDir(null), LOG_FILE_NAME)
            if (!logFile.exists()) {
                logFile.createNewFile()
            }

            FileOutputStream(logFile, true).use { fos ->
                PrintWriter(fos).use { pw ->
                    pw.write(message)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Failed to write log to file", e)
        }
    }
}